package nio.channel.filechannel;


import java.io.FileInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author charwayH
 * FileChannel的读操作
 */
public class FileChannelDemo1 {
    public static void main(String[] args) throws IOException {
        // 创建一个FileChannel
        RandomAccessFile aFile = new RandomAccessFile("/Users/charwayh/Desktop/java-myself/hello-nio/src/main/java/channel/1.txt", "rw");
        FileChannel channel = aFile.getChannel();
        // 创建Buffer
        ByteBuffer buf = ByteBuffer.allocate(1024);
        // 读取数据导Buffer中
        int byteRead = channel.read(buf);
        while (byteRead != -1){
            // 读取字节长度
            System.out.println("读取了:" + byteRead);
            buf.flip();
            while (buf.hasRemaining()){
                System.out.print((char) buf.get());
            }
            buf.clear();
            byteRead = channel.read(buf);
        }
        //关闭
        aFile.close();
        System.out.println("读取完成");
    }
}
